/**
 * 
 */
package spitfire.ksim.network;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import spitfire.ksim.node.KNode;
import spitfire.ksim.util.TPoint;

/**
 * @author Adam
 *
 */
public class KNetworkModuleImpl implements KNetworkModule {

	private final KNode hostNode;
	private KNetAddress netAddr;
	private KNetwork network;
	private double radioRange;
	private List<KNetworkModuleListener> listenerList = Collections.synchronizedList(
			new ArrayList<KNetworkModuleListener>());
	
	public KNetworkModuleImpl(KNode node, KNetwork network, double radioRange) {
		hostNode = node;
		this.radioRange = radioRange;
		connectNetwork(network);
	}

	/**
	 * @param network
	 */
	@Override
	public void connectNetwork(KNetwork network) {
		if (network == null) {
			throw new NullPointerException("Network cannot be null");
		}
		if (this.network != null) {
			disconnectNetwork();
		}
		this.network = network; 
		netAddr = network.register(this);
	}

	@Override
	public void disconnectNetwork() {
		network.deregister(this);
		network = null;
		netAddr = null;
	}
	
	@Override
	public KNode getHost() {
		return hostNode;
	}

	@Override
	public void setNetAddr(KNetAddress netAddr) {
		this.netAddr = netAddr;
	}

	@Override
	public KNetAddress getNetAddr() {
		return netAddr;
	}

	@Override
	public KNetwork getNetwork() {
		return network;
	}
	
	@Override
	public TPoint getLocation() {
		return hostNode.getLocation();
	}

	@Override
	public void addNetworkModuleListener(KNetworkModuleListener l) {
		listenerList.add(l);
	}
	
	@Override
	public void removePacketRecvListener(KNetworkModuleListener l) {
		listenerList.remove(l);
	}

	@Override
	public void send(KNetAddress destination, Object payload) {
		network.transmit(new KPacket(getNetAddr(), destination, payload));
	}
	
	@Override
	public void recv(KPacket packet) {
		if (packet.getDstAddr().equals(getNetAddr())
				|| packet.getDstAddr() == KNetAddress.BROADCAST_ADDR) {
			// accept the packet and inform listeners
			synchronized(listenerList) {
				for (KNetworkModuleListener l : listenerList) {
					l.onPacketRecv(packet.getSrcAddr(), packet.getPayload());
				}
			}
		} else {
			// not for me, discard the packet(do nothing)
		}
	}

	@Override
	public boolean adjacentWith(KNetworkModule netModule) {
		return (TPoint.dist(getLocation(), netModule.getLocation()) < radioRange);
	}
}
